package com.sale.system.controller;

import com.sale.common.core.constant.Constants;
import com.sale.common.core.domain.R;
import com.sale.common.core.web.controller.BaseController;
import com.sale.common.log.annotation.Log;
import com.sale.common.log.enums.BusinessType;
import com.sale.common.mybatis.core.page.PageQuery;
import com.sale.common.mybatis.core.page.TableDataInfo;
import com.sale.system.api.domain.dto.SysConverterManagementDto;
import com.sale.system.domain.dto.ConverterManagementDto;
import com.sale.system.domain.vo.ConverterManagementVo;
import com.sale.system.domain.vo.OrderReviewVo;
import com.sale.system.export.ConverterManagementExport;
import com.sale.system.export.ConverterManagementimportExport;
import com.sale.system.service.ConverterManagementService;
import com.sale.system.util.ExcelUtil;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.List;

/**
 * 加工商管理控制层
 */
@RestController
@RequestMapping("/converter-management")
public class ConverterManagementController extends BaseController {

    @Resource
    ConverterManagementService converterManagementService;

    /**
     * 加工商管理列表
     */
//    @RequiresPermissions("order:subcontracting:converter:list")
    @GetMapping("/list")
    public TableDataInfo<ConverterManagementDto> list(ConverterManagementVo converterManagementVo, PageQuery pageQuery) {
        //查询加工商列表
        return converterManagementService.getList(converterManagementVo, pageQuery);
    }

    /**
     * 加工商新增
     */
//    @RequiresPermissions("order:subcontracting:converter:add")
    @Log(title = "加工商新增", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public R<Void> add(@Validated @RequestBody ConverterManagementVo converterManagementVo) throws Exception {
        return toAjax(converterManagementService.addConverter(converterManagementVo));
    }

    /**
     * 加工商修改
     */
//    @RequiresPermissions("order:subcontracting:converter:edit")
    @Log(title = "加工商修改", businessType = BusinessType.UPDATE)
    @PostMapping("/update")
    public R<Void> update(@Validated @RequestBody ConverterManagementVo converterManagementVo) throws Exception {
        return toAjax(converterManagementService.updateConverterById(converterManagementVo));
    }

    /**
     * 删除加工商
     */
//    @RequiresPermissions("order:subcontracting:converter:remove")
    @Log(title = "删除加工商", businessType = BusinessType.DELETE)
    @DeleteMapping("/delete/{ids}")
    public R<Void> view(@PathVariable("ids") String ids) throws Exception {
        return toAjax(converterManagementService.getDeleteByIds(ids));
    }

    /**
     * 查看加工商信息
     */
//    @RequiresPermissions("order:subcontracting:converter:query")
    @GetMapping("/view/{id}")
    public R<ConverterManagementDto> getConverterView(@PathVariable("id") Long id) {
        return R.ok(converterManagementService.getConverterById(id));
    }

    /**
     * 冻结加工商
     */
//    @RequiresPermissions("order:subcontracting:converter:frozen")
    @Log(title = "冻结加工商", businessType = BusinessType.UPDATE)
    @GetMapping("/frozen/{id}")
    public R<Void> frozenSupplier(@PathVariable("id") Long id) {
        return toAjax(converterManagementService.frozenSupplier(id));
    }

    /**
     * 解冻加工商
     */
//    @RequiresPermissions("order:subcontracting:converter:thaw")
    @Log(title = "解冻加工商", businessType = BusinessType.UPDATE)
    @GetMapping("/thaw/{id}")
    public R<Void> thawSupplier(@PathVariable("id") Long id) {
        return toAjax(converterManagementService.thawSupplier(id));
    }

    /**
     * 撤销审核
     */
//    @RequiresPermissions("order:subcontracting:converter:revoke")
    @Log(title = "撤销审核", businessType = BusinessType.UPDATE)
    @GetMapping("/revoke/{id}")
    public R<Void> revokeApproval(@PathVariable("id") Long id) {
        return toAjax(converterManagementService.revokeApproval(id));
    }


//    /**
//     * 生成加工商导入模板
//     */
//    @PostMapping("/converterTemplate")
//    public AjaxResult supplierTemplate(HttpServletResponse response) throws IOException {
//        ExcelUtil<ConverterManagementimportExport> excelUtil = new ExcelUtil<ConverterManagementimportExport>(ConverterManagementimportExport.class);
//        excelUtil.exportTemplate(response, null, "加工商信息.xlsx");
//        return AjaxResult.success();
//    }

    /**
     * 生成加工商导入模板
     */
    @PostMapping("/downTemplate")
    public void downTemplate(HttpServletResponse response) throws IOException {
        String name = "加工商";
        String fileName = Constants.TEMPLATE_URL + "导入" + name + ".xlsx";
        File file = new File(fileName);
        ByteArrayOutputStream baos = null;
        ServletOutputStream out = null;
        try {

            InputStream inStream = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int len;
            baos = new ByteArrayOutputStream();
            while ((len = inStream.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("导入加工商.xlsx", "UTF-8"));
            out = response.getOutputStream();
            out.write(baos.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            baos.flush();
            baos.close();
            out.flush();
            out.close();
        }
    }


    /**
     * 加工商信息导出
     */
//    @RequiresPermissions("order:subcontracting:converter:export")
    @PostMapping("/converterMessageExport")
    public R<Void> mouldMessageExport(HttpServletResponse response, ConverterManagementVo converterManagementVo) throws IOException {
        List<ConverterManagementExport> infoExport = converterManagementService.getInfoExport(converterManagementVo);
        ExcelUtil<ConverterManagementExport> excelUtil = new ExcelUtil<ConverterManagementExport>(ConverterManagementExport.class);
        excelUtil.excelWriter(response, infoExport, "加工商信息.xlsx");
        return R.ok();
    }

    /**
     * 加工商信息导入
     */
    @PostMapping("/converterMessageImport")
//    @RequiresPermissions("order:subcontracting:converter:import")
    @Log(title = "加工商信息导入", businessType = BusinessType.INSERT)
    public R<Void> mouldMessageImport(MultipartFile file) throws IOException {
        ExcelUtil<ConverterManagementimportExport> excelUtil = new ExcelUtil<ConverterManagementimportExport>(ConverterManagementimportExport.class);
        List<ConverterManagementimportExport> coCustomer = excelUtil.importExcel(file.getInputStream());
        return R.ok(converterManagementService.importMouldData(coCustomer));
    }

    /**
     * 提交审核
     */
//    @RequiresPermissions("order:subcontracting:converter:reviewSubmit")
    @Log(title = "提交审核", businessType = BusinessType.UPDATE)
    @GetMapping("/reviewSubmit/{id}")
    public R<Void> reivewSubmit(@PathVariable("id") Long id) {
        return toAjax(converterManagementService.reivewSubmit(id));
    }

    /**
     * 加工商审核
     */
//    @RequiresPermissions("order:subcontracting:converter:converterReview")
    @Log(title = "加工商审核", businessType = BusinessType.UPDATE)
    @PostMapping("/converterReview")
    public R<Void> converterReview(@Validated @RequestBody OrderReviewVo orderReviewVo) throws Exception {
        return toAjax(converterManagementService.converterReview(orderReviewVo));
    }

    /**
     * 根据id获取详情数据（dubbo）
     */
    @GetMapping("/getConverterById")
    public SysConverterManagementDto getConverterById(Long id) {
        return converterManagementService.getViewById(id);
    }

    /**
     * 根据编码获取详情数据（dubbo）
     */
    @GetMapping("/getConverterByCode")
    public SysConverterManagementDto getConverterByCode(String code) {
        return converterManagementService.getViewByCode(code);
    }

}
